package com.qicheng.wlhyspider.anhui.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qicheng.wlhyspider.anhui.dao.AhDriverRepository;
import com.qicheng.wlhyspider.anhui.entity.AhDriverEntity;
import com.qicheng.wlhyspider.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 安徽驾驶员
 */
@Service
@Slf4j
public class AhDriverService {
    private final AhDriverRepository ahDriverRepository;
    private final RedisUtils redisUtils;

    public AhDriverService(AhDriverRepository ahDriverRepository, RedisUtils redisUtils) {
        this.ahDriverRepository = ahDriverRepository;
        this.redisUtils = redisUtils;
    }


    public Result saveAll(Integer page, String startDate, String endDate, String companyId) {
        String url = String.format("https://wlhy.ahyg.com.cn/basis/driver/list?page=%s&limit=%s&messageSendingDateTimeRange=%s+~+%s",
                page, 10000, startDate, endDate);
        Object o = redisUtils.get(Constants.AH_TOKEN);
        HttpResponse httpResponse = HttpUtil.createGet(url)
                .header("x-auth-token", o + "")
                .execute();
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<AhDriverEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), AhDriverEntity.class);
            for (AhDriverEntity ahDriverEntity : list) {
                ahDriverEntity.setCompanyId(companyId);
            }
            ahDriverRepository.saveAll(list);


            log.info(String.format("驾驶员查询，%s到%s，第%s页，总页数%s", startDate, endDate, page, result.getPages()));
            if (page < result.getPages()) {
                page++;
                return saveAll(page, startDate, endDate, companyId);
            }

        } else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
            return Results.error("登录信息失效");
//            LoginUtils.login();
//             return saveAll(page, startDate, endDate);
        } else {
            log.info("查询失败");
            return Results.error("查询失败");
        }
        log.info("返回：插入成功");
        return Results.success();
    }

    public Result saveDetail() {
        List<AhDriverEntity> list = ahDriverRepository.findAllByIsDetailIsNull();
        List<List<AhDriverEntity>> lists = ListUtil.splitAvg(list, list.size() / 16);
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (List<AhDriverEntity> ahDriverEntities : lists) {
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                for (AhDriverEntity ahDriverEntity : ahDriverEntities) {
                    String url = String.format("https://wlhy.ahyg.com.cn/basis/driver/id?id=%s&_=1722159143227",
                            ahDriverEntity.getId());
                    Object o = redisUtils.get(Constants.AH_TOKEN);
                    HttpResponse httpResponse = HttpUtil.createGet(url)
                            .header("x-auth-token", o + "")
                            .execute();
                    if (httpResponse.getStatus() == 200) {
                        String body = httpResponse.body();
                        Result<AhDriverEntity> result = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), Result.class);
                        AhDriverEntity ahDriverEntityDetail = JSONObject.parseObject(JSONObject.toJSONString(result.getResult()), AhDriverEntity.class);
                        String[] nullPropertyNames = PropertyUtil.getNullPropertyNames(ahDriverEntityDetail);
                        BeanUtils.copyProperties(ahDriverEntityDetail, ahDriverEntity, nullPropertyNames);
                        ahDriverEntity.setIsDetail(1);
                        ahDriverRepository.save(ahDriverEntity);

                    } else if (httpResponse.getStatus() == 203) {
                        log.info("登录信息失效");
                        throw new RuntimeException("登录信息失效");
//            return "返回：登录信息失效";
//            LoginUtils.login();
//                 return saveAll(page, startDate, endDate);
//                         return "返回：登录信息失效";
                    } else {
                        log.info("查询失败");
                        throw new RuntimeException("查询失败");
                        // return "返回：查询失败";
                    }
                }
            });
            futures.add(voidCompletableFuture);

        }
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        try {
            voidCompletableFuture.get();
            return Results.success();
        } catch (Exception e) {
            return Results.error("查询失败" + e.getMessage());
        }

    }

}
